package com.microblogforsim.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.microblogforsim.R;
import com.microblogforsim.activity.HomePageActivity;
import com.microblogforsim.model.TextModel;
import com.microblogforsim.model.Topics;
import com.microblogforsim.ui.PictureGridView;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import static com.microblogforsim.utils.LogUtils.TAG;

public class TextAdapter extends BaseAdapter {
    private Context context;

    private ArrayList<Topics.DataBean> data;
    private int size = 0;
    //type 1 @
    private int good = 0;//type 2
    private int share = 0;//type 6
    private int comment = 0;//type 3 4
    private boolean isGood = false;

    public TextAdapter(Context context) {
        this.context = context;
    }


    public void replayAll(ArrayList<Topics.DataBean> data) {

        if (this.data == null) this.data = new ArrayList<>();
        this.data.clear();
        if (data != null && data.size() > 0) this.data.addAll(data);
        notifyDataSetChanged();
    }

    public void add(Topics.DataBean model) {
        if (this.data == null) this.data = new ArrayList<>();
        if (model != null) this.data.add(model);
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        return data.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }


    private void to_HomePage(int position) {
        Intent intent = new Intent(context, HomePageActivity.class);
        Bundle bundle = new Bundle();
        Topics.DataBean.UserBean userBean = new Topics.DataBean.UserBean();
        userBean = this.data.get(position).getUser().get(0);
        bundle.putSerializable("user", userBean);
        intent.putExtras(bundle);
        context.startActivity(intent);
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        Log.d("cnm", "getView: " + data.size());
        final ViewHolder holder;
        final Drawable igood = context.getResources().getDrawable(R.drawable.ic_good);
        final Drawable gooded = context.getResources().getDrawable(R.drawable.ic_gooded);
        igood.setBounds(0, 0, igood.getMinimumWidth(), igood.getMinimumHeight());
        gooded.setBounds(0, 0, gooded.getMinimumWidth(), gooded.getMinimumHeight());
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.index_list_item, parent, false);
            holder = new ViewHolder();
            holder.gridview = convertView.findViewById(R.id.index_list_gridView);
            holder.img_src = convertView.findViewById(R.id.index_list_item_upic);
            holder.tv_name = convertView.findViewById(R.id.index_list_item_uname);
            holder.tv_time = convertView.findViewById(R.id.index_list_item_time);
            holder.tv_from = convertView.findViewById(R.id.index_list_item_from);
            holder.tv_commont = convertView.findViewById(R.id.index_list_item_commont);
            holder.tv_content = convertView.findViewById(R.id.index_list_item_content);
            holder.tv_good = convertView.findViewById(R.id.index_list_item_good);
            holder.tv_share = convertView.findViewById(R.id.index_list_item_share);
            holder.btn_share = convertView.findViewById(R.id.index_list_item_btn_share);
            holder.btn_comment = convertView.findViewById(R.id.index_list_item_btn_commont);
            holder.btn_good = convertView.findViewById(R.id.index_list_item_btn_good);
            convertView.setTag(holder);   //将Holder存储到convertView中
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        //获取当前的图片数目
        int num = 0;
        if (this.data.get(position).getImg().size() > 0) {
            num = position % this.data.get(position).getImg().size() + 1;
        } else {
            num = 0;
        }
        int col = 1;//默认列数

        if (num == 1) {
            holder.gridview.setNumColumns(1);
            col = 1;
        } else if (num == 2 || num == 4) {
            holder.gridview.setNumColumns(2);
            col = 2;
        } else {
            holder.gridview.setNumColumns(3);
            col = 3;
        }
        holder.gridview.setAdapter(new MyGridViewAdapter(context, num, col, this.data.get(position).getImg()));
        holder.tv_name.setText(this.data.get(position).getUser().get(0).getUserName());
        holder.tv_time.setText(this.data.get(position).getT());
        holder.tv_content.setText(this.data.get(position).getContent());//data.get(position).getContent()
        if (this.data.size() != size) {
            getAction(this.data.get(position).getAction(), holder);
            size = this.data.size();
        }
//        getAction(this.data.get(position).getAction(),holder);
        holder.tv_commont.setText(this.comment + "");
        holder.tv_share.setText(this.share + "");
        holder.tv_good.setText(this.good + "");
//        点击头像进入用户详情页
        holder.img_src.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                to_HomePage(position);
            }
        });
        //点击时间
        holder.tv_time.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        //点击名字
        holder.tv_name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                to_HomePage(position);
            }
        });
//        分享按钮点击事件
        holder.btn_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(context, "分享", Toast.LENGTH_SHORT).show();
            }
        });
//        评论按钮点击事件
        holder.btn_comment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(context, "评论", Toast.LENGTH_SHORT).show();
            }
        });
//        点赞按钮点击事件
        holder.btn_good.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Toast.makeText(context, "点赞", Toast.LENGTH_SHORT).show();
                int num = Integer.valueOf(holder.tv_good.getText().toString());
                if (!holder.isGood) {
                    holder.tv_good.setCompoundDrawables(gooded, null, null, null);
                    num++;
                    good++;
                } else {
                    num--;
                    holder.tv_good.setCompoundDrawables(igood, null, null, null);
                    good--;
                }
                holder.good = num;
                holder.tv_good.setText(num + "");
                isGood = !isGood;
                holder.isGood = !holder.isGood;
            }
        });
        //使用Glide加载图片
        Glide.with(context)
                //加载地址
                .load(this.data.get(position).getUser().get(0).getImg())
                //加载失败时，设置默认的图片
                .placeholder(R.drawable.loading)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                //显示的位置
                .into(holder.img_src);
        return convertView;
    }

    class ViewHolder {
        PictureGridView gridview;
        TextView tv_commont;//评论数
        TextView tv_good;//点赞数
        TextView tv_share;//分享数
        ImageView img_src;//头像
        TextView tv_from;//来自
        TextView tv_name;//名字
        TextView tv_time;//时间
        TextView tv_content;//d内容
        LinearLayout btn_share;//分享按钮
        LinearLayout btn_comment;//评论按钮
        LinearLayout btn_good;//点赞按钮
        int good = 0;
        int share = 0;
        int comment = 0;
        boolean isGood = false;
    }

    private void getAction(List<Topics.DataBean.ActionBean> actionBean, ViewHolder holder) {
        int i = 0;
        this.good = 0;
        this.share = 0;
        this.comment = 0;
        holder.good = 0;
        holder.comment = 0;
        holder.share = 0;
        SharedPreferences sharedPreferences = context.getSharedPreferences("data", Context.MODE_PRIVATE);

        while (i < actionBean.size()) {
            switch (actionBean.get(i).getType()) {
                case 1:
                    break;
                case 2:
                    if (actionBean.get(i).getA().equals(sharedPreferences.getString("openid", ""))) {
                        isGood = true;
                        holder.isGood = true;
                    }
                    this.good++;
                    holder.good++;
                    break;
                case 3:
                    this.comment++;
                    holder.comment++;
                    break;
                case 4:
                    this.comment++;
                    holder.comment++;
                    break;
                case 6:
                    holder.share++;
                    this.share++;
                    break;
            }
            i++;
        }

//        if (holder.good > 0) holder.isGood = true;
//        holder.tv_good.setText(holder.good+"");
//        holder.tv_commont.setText(holder.comment+"");
//        holder.tv_share.setText(holder.share+"");
//        if (this.good > 0) this.isGood = true;
        holder.tv_good.setText(this.good + "");
        holder.tv_commont.setText(this.comment + "");
        holder.tv_share.setText(this.share + "");
    }

//    public Bitmap getLocalOrNetBitmap(String url) {
//        Bitmap bitmap = BitmapFactory.decodeResource(this.context.getResources(),
//                R.drawable.shuai);
//        if (url != null) {
//            InputStream in = null;
//            BufferedOutputStream out = null;
//            try {
//                //读取图片输入流
//                in = new BufferedInputStream(new URL(url).openStream(), 2 * 1024);
//                //准备输出流
//                final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
//                out = new BufferedOutputStream(dataStream, 2 * 1024);
//                byte[] b = new byte[1024];
//                int read;
//                //将输入流变为输出流
//                while ((read = in.read(b)) != -1) {
//                    out.write(b, 0, read);
//                }
//                out.flush();
//                //将输出流转换为bitmap
//                byte[] data = dataStream.toByteArray();
//                bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
//                data = null;
//                return bitmap;
//            } catch (IOException e) {
//                e.printStackTrace();
//                return bitmap;
//            }
//        }
//        return bitmap;
//    }

    //异步加载图片
//    private void asyncloadImage(final ImageView imageView, final String uri) {
//        final Handler mHandler = new Handler() {
//            @Override
//            public void handleMessage(Message msg) {
//                super.handleMessage(msg);
//                if (msg.what == 1) {
//                    Bitmap bitmap = (Bitmap) msg.obj;
//                    if (imageView != null && uri != null) {
//                        imageView.setImageBitmap(bitmap);
//                    }
//
//                }
//            }
//        };
//        // 子线程，开启子线程去下载或者去缓存目录找图片，并且返回图片在缓存目录的地址
//        Runnable runnable = new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    //这个URI是图片下载到本地后的缓存目录中的URI
//                    if (uri != null) {
//                        Bitmap bitmap = getLocalOrNetBitmap(uri);
//                        Message msg = new Message();
//                        msg.what = 1;
//                        msg.obj = bitmap;
//                        mHandler.sendMessage(msg);
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//        };
//        new Thread(runnable).start();
//    }

}

